﻿using Magicodes.ExporterAndImporter.Excel.AspNetCore;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NP.BPMReportPlatform.HR.Dto;
using NP.BPMReportPlatform.SystemSettings.Dto;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.SystemSettings
{
    /// <summary>
    /// KeyValues字典 配置
    /// </summary>
    [ApiController]
    [Route("api/KeyValuesConfiguration")]
    public class KeyValuesConfigurationController : BPMReportPlatformController
    {
        private readonly IKeyValuesConfigurationAppService _configurationAppService;
        public KeyValuesConfigurationController(IKeyValuesConfigurationAppService configurationAppService)
        {
            _configurationAppService = configurationAppService;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetAllAsync")]
        public async Task<PagedResultDto<KeyValuesConfigurationOutput>> GetAllAsync([FromBody] KeyValuesConfigurationInput input)
        {
            return await _configurationAppService.GetAllAsync(input);
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SaveAsync")]
        public async Task SaveAsync([FromBody] SaveKeyValuesConfigurationInput input)
        {
            await _configurationAppService.SaveAsync(input);
        }

        /// <summary>
        /// 删除配置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("DeleteAsync")]
        public async Task DeleteAsync([FromQuery] string id)
        {
            await _configurationAppService.DeleteAsync(id);
        }

        /// <summary>
        /// 批量导入Excel
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("ImporterExcelAsync")]
        public async Task<ImportResultExt<ImportKeyValuesTemplate>> ImporterExcelAsync(IFormFile file)
        {
            if (file == null)
            {
                var res = new ImportResultExt<ImportKeyValuesTemplate>();
                res.Exception = new Exception("请上传文件！");
                return res;
            }
            var s = file.OpenReadStream();
            var bytes = StreamToBytes(s);
             s.Close();
            return await _configurationAppService.ImporterExcel(bytes);
        }
        private byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }
    }
}
